iT邦幫忙

1

動態載入CSS/JS = 在js中載入CSS或JS

  • 分享至 

  • xImage
  •  

動態載入CSS

準備style.css

p {
    color: green;
    text-align: center;
} 

準備HTML


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <script>
        function dynamicLoadCss(url) {
            var head = document.getElementsByTagName('head')[0];
            var mycss = document.createElement('link');
            mycss.type = 'text/css';
            mycss.rel = 'stylesheet';
            mycss.href = url;
            head.appendChild(mycss);
        }
        if (1 == 1) {
            dynamicLoadCss("style.css");//在這裡Load
        }
    </script>

    <p>This is a paragraph.</p>
</body>
</html>

動態載入JS

準備myscript.js
alert("hi,everybody");

準備HTML

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <script> 
        function dynamicLoadJS(url) {
            var head = document.getElementsByTagName('head')[0];
            var myscript = document.createElement("script");
            myscript.type = "text/javascript";
            myscript.src = url;
            head.appendChild(myscript);
        } 
        if (1 == 1) {
            dynamicLoadJS("myscript.js");//在這裡load
        }  
    </script>

    <p>This is a paragraph.</p>
</body>
</html>

ref
http://www.victsao.com/blog/81-javascript/135-javascript-linkcss
https://tw.saowen.com/a/02517a131abc7dcd06edb4563dcafe0debc1b636d414143dad895cfc0831552e


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言